/*
https://leetcode-cn.com/problems/3sum-closest/solution/zui-jie-jin-de-san-shu-zhi-he-by-leetcode-solution/
 */
import java.util.Arrays;

public class Solution16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ans=Integer.MAX_VALUE/2;
        for (int i=0;i<nums.length-2;i++){
            int b=i+1,c=nums.length-1;
            while (b<c){
                if (Math.abs(nums[i]+nums[b]+nums[c]-target)<Math.abs(ans-target)){
                    ans=nums[i]+nums[b]+nums[c];
                }
                if (nums[i]+nums[b]+nums[c]>=target){
                    c--;
                }else{
                    b++;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution16().threeSumClosest(new int[]{1,1,-1,-1,3},-1));
    }
}
